package com.link.base.base.message.push.service;

import com.link.base.base.message.push.model.PushInfo;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.util.RedisUtil;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Component;
import com.xiaomi.xmpush.server.*;

/**
 * 小米推送
 *
 * @author ouyangzhenqiang
 * @date 2019/08/12 16:03
 */
@Component
public class XiaomiPushServiceImpl {

    /**
     * 推送消息
     *
     * @author ouyangzhenqiang
     * @date 2019/08/12 15:58
     */
    void xiaomiPush(PushInfo record) throws Exception {
        LinkRedisClient j = null;
        try {
            j = RedisUtil.getJedis();
            String redisKey = "APP_PUSH_CONFIG";
            String xmPushAppSecret = j.hget(redisKey, "xmPushAppSecret_" + record.getAppId());
            Constants.useOfficial();
            Sender sender = new Sender(xmPushAppSecret);
            String messagePayload = record.getPushNote();
            String description = record.getPushNote();
            Message message = new Message.Builder()
                .title(record.getPushTitle())
                .description(description).payload(messagePayload)
                .restrictedPackageName(record.getAppId())
                .notifyType(1)
                .extra(Constants.EXTRA_PARAM_NOTIFY_EFFECT, Constants.NOTIFY_LAUNCHER_ACTIVITY)
                .build();
            Result result = sender.send(message, record.getPushServiceToken(), 0);
            LCLogger.info().withMessageKey("xiaomiPush").withMessage("sendPush result => " + result).flush();
            if (0 != result.getErrorCode().getValue()) {
                throw new BasicServiceException(result.getReason());
            }
        } finally {
            RedisUtil.returnResource(j);
        }
    }

}
